package NewCoder;

import java.util.ArrayDeque;
import java.util.Deque;

public class BM94 {
    public long maxWater (int[] arr) {
        // write code here
        Deque<Integer> d=new ArrayDeque<>();
        long ans=0;
        for(int i=0;i<arr.length;i++){
            while(!d.isEmpty() && arr[d.peek()]<arr[i]){
                int top=d.pop();
                if(d.isEmpty()){
                    break;
                }
                int left=d.peek();
                int w=i-left-1;
                int h=Math.min(arr[i],arr[left])-arr[top];
                ans+=(w*h);
            }
            d.push(i);
        }
        return ans;
    }
}
